<template>
  <inline-Modal
    :visible="visible"
    :title="menuName"
    :showOk="false"
    @cancel="handelCancel()"
  >
    <a-button
      type="primary"
      class="add-btn"
      :loading="submitLoading"
      @click="handelOk()"
    >
      确定
    </a-button>
    <div class="editorPage-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <div class="warp-container">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="工程类型">
                <a-select
                  allowClear
                  placeholder="请选择"
                  v-model="form.engType"
                  showSearch
                  :filter-option="filterOption"
                  disabled
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in engineerTypeSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="立项类型">
                <a-select
                  allowClear
                  placeholder="请选择"
                  v-model="form.type"
                  showSearch
                  :filter-option="filterOption"
                  disabled
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in approvalTypeSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item
            :key="item.uuid"
            v-for="(item, index) in form.childList"
            :label="item.name"
            :prop="'childList.' + index + '.files'"
            :rules="{
              required: true,
              message: '请选择' + item.name,
            }"
          >
            <bjUploadFile
              :count="20"
              v-model="item.files"
              @preview="viewFile($event)"
              @download="downloadFile($event)"
              @change="
                handleUpLoadFile($event, {
                  idx: index,
                  domain: 'files',
                })
              "
              :replaceFields="{
                fileName: 'fileName',
                fileSize: 'fileSize',
                fileType: 'fileType',
              }"
            ></bjUploadFile>
          </a-form-model-item>
          <a-form-model-item label="备注">
            <a-textarea v-model="form.remark" :rows="4"></a-textarea>
          </a-form-model-item>
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="提交人">
                <a-input v-model="form.creator" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="提交时间">
                <a-input v-model="form.createTime" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </div>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </inline-Modal>
</template>

<script>
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { axios } from "@/utils/request";
//附件上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { detailCanton, saveCanton } from "@/api/cantonManage";
import { getDicItemByCode } from "@/api/common.js";
export default {
  components: {
    IconFont,
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        uuid: "",
        //项目类型
        engType: undefined,
        //立项类型
        type: undefined,
        //文件
        childList: [],
        //备注
        remark: "",
        //创建人
        creator: "",
        //创建时间
        createTime: "",
      },
      rules: {
        engType: [
          {
            required: true,
            message: "请选择项目类型",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择立项类型",
          },
        ],
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      submitLoading: false,
      //项目类型
      engineerTypeSource: [],
      //立项类型
      approvalTypeSource: [],
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getData() {
      await this.getDetail();
      //项目类型
      this.engineerTypeSource = await this.getDicCodeData("engineeringType");
      //立项类型
      this.approvalTypeSource = await this.getDicCodeData(
        "projectApprovalType"
      );
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //详情
    getDetail() {
      detailCanton({
        code: "TDSXBL",
      })
        .then((res) => {
          this.form = {
            //批注id
            uuid: res?.uuid ?? "",
            //项目类型
            engType: res?.engType,
            //立项类型
            type: res?.type,
            //文件
            childList: res?.childList ?? [],
            //备注
            remark: res.remark,
            //创建人
            creator: res.creator,
            //创建时间
            createTime: res.createTime,
          };
          this.form.childList.forEach((item) => {
            item.files = JSON.parse(item.files ?? "[]");
          });
        })
        .catch((_) => {});
    },
    //表单提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            uuid: form.uuid,
            //项目类型
            engType: form?.engType,
            //立项类型
            type: form?.type,
            //文件
            list: [],
            //备注
            remark: form.remark,
          };
          form.childList.forEach((item) => {
            const fileList = item.files.map(
              ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
            );
            formJson.list.push({
              uuid: item.detailId,
              name: item.name,
              files: JSON.stringify(fileList),
            });
          });
          this.submitLoading = true;
          saveCanton(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("处理成功", 1.5);
                this.handelCancel();
              } else {
                this.$message.error(res?.message ?? "处理失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.submitLoading = false;
            });
        }
      });
    },

    //上传附件
    handleUpLoadFile({ file, index }, item) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      let { idx, domain } = item;
      this.$set(this.form["childList"][idx][domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(
            this.form["childList"][idx][domain][index],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(this.form["childList"][idx][domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form["childList"][idx][domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(
            this.form["childList"][idx][domain][index],
            "loading",
            false
          );
        });
    },

    //下载
    downloadFile(row) {
      let { url } = row;
      downloadDfs(url);
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    handelCancel() {
      this.$emit("update:visible", false);
      this.$parent.getData();
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 130px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  .add-btn {
    position: absolute;
    top: 10px;
    right: 90px;
  }
  .editorPage-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;

    .warp-container {
      padding-right: 110px;
      box-sizing: border-box;
      /deep/.bj-upload-file {
        .choosed-file-warp {
          width: 100%;
          .file-list {
            .base-info {
              background: rgba(24, 144, 255, 0.1);
            }
          }
        }
      }
    }
  }
}
</style>
